package com.furns.filter;

import com.furns.entity.Member;
import com.furns.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对用户登录做校验
 * @Author LuoJiaCheng
 * @ID 2240129126
 * @Version 1.0
 */

public class AuthFilter implements Filter {
    private List<String> excludedUrls;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String strExcludedUrls = filterConfig.getInitParameter("excludedUrls");
        String[] split = strExcludedUrls.split(",");
         excludedUrls = Arrays.asList(split);

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;

        //不包含初始化参数，拦截
        String url = request.getServletPath();
        if(!excludedUrls.contains(url)){
            Member member = (Member) request.getSession().getAttribute("member");
            if(null==member){
                if(!WebUtils.isAjaxRequest(request)){
                    request.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest,servletResponse);

                }else{
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("url","views/member/login.jsp");
                    String resultUrl = new Gson().toJson(resultMap);
                    servletResponse.getWriter().write(resultUrl);

                }
                    return;
            }
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
